package com.zzuli.yxypre.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzuli.yxypre.comment.R;
import com.zzuli.yxypre.entity.User;
import com.zzuli.yxypre.entity.WxConstant;
import com.zzuli.yxypre.mapper.UserMapper;
import com.zzuli.yxypre.utils.HttpClientUtils;
import com.zzuli.yxypre.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.Objects;


/**
 * @auther pony
 * @create 2023-04-30 17:42
 */
@Controller
@RequestMapping("api/ucenter/wx")
@CrossOrigin(origins = "*")
public class WxApiController {
    @Autowired
    private WxConstant wxConstant;

    @Autowired
    private UserMapper userMapper;

    /**
     * 手机扫码，并且确认后，会执行此方法
     * @param code 临时票据，类似于验证码
     * @param state 原样传递，，没啥用
     * @return
     */
    @GetMapping("callback")
    private String callback(String code, String state){
        String token = null;
        try {
            System.out.println(code);
            System.out.println(state);

            /*1、使用 code 去访问 微信提供的一个接口
            微信的接口会返回两个值 accsess_token 和 openid
            accsess_token : 访问微信的凭证
            openid : 微信用户的唯一标识 相当于数据库里的 id*/
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
            "?appid=%s" +
            "&secret=%s" +
            "&code=%s" +
            "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    wxConstant.getAppId() ,
                    wxConstant.getAppSecret(),
                    code);
            //使用 httpclient 发送请求，得到返回结果
            // {"access_token":"68_WmlhmszYmwYKgCuMbIYyIuBqPjGYjnqdlVdskFJfPwMTY58yKckF1cZg3IrRoei8_STkfPoR5YVePrWMeLLXpyyY2NxHBEp466zZAGWESrE","expires_in":7200,"refresh_token":"68_qX3x3yhfcRh5BUse4B0iQXeZpeOQPUQ-RezN_tipHwfwatdgjlnUFtk5dLLPkOFYvdgA15vXBEbksbjEQqfn-AQf57ofrHvv7UUV_7gfzvg","openid":"o3_SC55KuZU0oc8DFhOtfVtkmvjY","scope":"snsapi_login","unionid":"oWgGz1F8spKNKg_gH07IT1CNRme8"}
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //  获取 access_token 和 openid
            // 将 json 转 map , 通过 map key 获取 value
            JSONObject map = JSON.parseObject(accessTokenInfo);
            Object access_token = map.get("access_token");
            Object openid = map.get("openid");
            // 再将 对象转 String 带 "内容"，去掉 ""
            String accessToken = JSON.toJSONString(access_token).substring(1, JSON.toJSONString(access_token).length()-1);
            String openId = JSON.toJSONString(openid).substring(1, JSON.toJSONString(openid).length()-1);

            System.out.println(accessToken);
            System.out.println(openId);

            //2、根据 openId 判断用户是否注册，没注册的获取扫码人信息，添加数据库
            LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
            // 根据 openId 查
            qw.eq(User::getOpenId, openId);
            User selectOne = userMapper.selectOne(qw);

            if (Objects.isNull(selectOne)){ // 数据库没有
                /*3、 使用 accessToken 和 openId 再去访问 微信提供的一个接口
                 * 返回 扫码人的信息*/
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openId);
                //{"openid":"o3_SC55KuZU0oc8DFhOtfVtkmvjY","nickname":"pony","sex":0,"language":"","city":"","province":"","country":"","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/AMuCCricwj9dAka0GjKGzPE15DsRVw6TaxdSpia94gNEia0bBWB6Y7fqKHpKibJQ66UptxxLrDZN6rfF3jG6YSEwXQ\/132","privilege":[],"unionid":"oWgGz1F8spKNKg_gH07IT1CNRme8"}
                //包含 用户id 昵称 性别(一直为0，微信已经不让获取了) 城市（一般为空） 国家 头像
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(resultUserInfo);

                // 获取扫码人的 昵称 性别 头像
                JSONObject userInfoMap = JSON.parseObject(resultUserInfo);
                Object nickname = userInfoMap.get("nickname");
                Object headimgurl = userInfoMap.get("headimgurl");
                // 再将 对象转 String 带 "内容"，去掉 ""
                String nickName = JSON.toJSONString(nickname).substring(1, JSON.toJSONString(nickname).length()-1);
                String headImgurl = JSON.toJSONString(headimgurl).substring(1, JSON.toJSONString(headimgurl).length()-1);

                System.out.println(nickName);
                System.out.println(headImgurl);

                // 添加数据库
                User user = new User();
                user.setOpenId(openId);
                user.setNickName(nickName);
                user.setImg(headImgurl);
                userMapper.insert(user);

                //根据 openId 查询登录人的id
                LambdaQueryWrapper<User> selectQw = new LambdaQueryWrapper<>();
                selectQw.eq(User::getOpenId, openId);
                User result = userMapper.selectOne(selectQw);
                token = JwtUtils.getJwtToken(String.valueOf(result.getId()));

//                int insert = userMapper.insert(user);
//                if (insert==1){
////                    return R.success().message("注册成功！");
//                }
            } else{ //数据库有
                token = JwtUtils.getJwtToken(String.valueOf(selectOne.getId()));
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return "redirect:http://127.0.0.1:8848/yxy-pre/pages/index.html?token="+ token;
    }

    @ResponseBody
    @GetMapping("login")
    public R genQrConnect() {
        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
        "?appid=%s" +
        "&redirect_uri=%s" +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=%s" +
        "#wechat_redirect";
        // 回调地址
        String redirectUrl = wxConstant.getRedirectUrl() ; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            e.printStackTrace();
        }

        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                wxConstant.getAppId(),
                redirectUrl,
                "yxy");
        return R.success().message("微信登录验证码").data("codeUrl", qrcodeUrl);
//        return "redirect:" + qrcodeUrl;
    }
}
